package com.jlnk.androidfmc.adapter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.jlnk.androidfmc.database.PostDatabase;
import com.jlnk.androidfmc.entity.Post;
import com.jlnk.androidfmc.R;

import java.util.ArrayList;
import java.util.List;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
    private final PostDatabase postDatabase;
    private List<Post> posts;
    private PostDatabase db;

    // PostAdapter.java
    public void setData(List<Post> posts) {
        if (posts == null) {
            this.posts = new ArrayList<>();
        } else {
            this.posts.clear();
            this.posts.addAll(posts);
        }
        notifyDataSetChanged();
    }

    // 新的重载构造函数
    public PostAdapter(List<Post> posts, PostDatabase postDatabase) {
        this.posts = posts;
        this.postDatabase = postDatabase;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Post post = posts.get(position);
        holder.postContent.setText(post.getContent());

        // 从数据库获取图片数据
        byte[] imageByteArray = postDatabase.getPostImage(post.getId());
        if (imageByteArray != null) {
            // 将字节数组转换为Bitmap对象并设置到ImageView
            Bitmap bitmap = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
            holder.postImage.setImageBitmap(bitmap);
        } else {
            // 如果没有图片数据，设置默认图片
            holder.postImage.setImageResource(R.drawable.nongye);
        }
    }

    private void loadPostImage(ImageView imageView, long postId) {
        if (db != null) {
            byte[] imageByteArray = db.getPostImage(postId);
            if (imageByteArray != null) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
                imageView.setImageBitmap(bitmap);
            } else {
                // 设置默认图片
                imageView.setImageResource(R.drawable.n7);
            }
        }
    }

    @Override
    public int getItemCount() {
        return posts.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView postContent;
        ImageView postImage;

        public ViewHolder(View itemView) {
            super(itemView);
            postContent = itemView.findViewById(R.id.post_content);
            postImage = itemView.findViewById(R.id.post_image);
        }
    }
}